import axios from 'axios'
import vm from '../main'
import router from '../router'
import store from '../store/'

axios.defaults.withCredentials = true
axios.defaults.baseURL = window._config_.baseUrl
axios.defaults.timeout = 8000 // 请求超时8s

// 请求拦截器，取消重复请求
let requestList = [] // 请求信息list
let cancelToken = axios.CancelToken
// 取下上一个重复的请求
function requestPending(config){
  for(let i=0;i<requestList.length;i++){
    if(config.url.includes(requestList[i].url)){
      requestList[i].cancel()
      requestList.splice(i,1) // 取消请求后，删除该请求在数组中的位置(删除包括已成功返回的请求)
    }
  }
}
// 响应后删除该请求信息在数组中的位置(调不调用都无所谓)
function responsePending(response){
  let index = requestList.findIndex((item)=>response.config.url.includes(item.url))
  if(index!==-1) requestList.splice(index,1)
}

// 请求拦截，请求前获取token，并添加到头部
let whiteList = [`${window._config_.stockUrl}`,`${window._config_.printerConfig}`,'logincheck'] // 1.新哥那边获取库存域名，2.获取打印机域名，3.登录接口
axios.interceptors.request.use((request)=>{
  requestPending(request)
  request.cancelToken = new cancelToken(function executor(c){//本次axios请求的配置添加cancelToken
    requestList.push({
      url:request.url,
      cancel:c
    })
  })
  let isInWhiteList = false
  for(let i=0;i<whiteList.length;i++){
    if(request.url.includes(whiteList[i])){
      isInWhiteList = true
      break
    }
  }
  if(!isInWhiteList){  // 白名单，不能设置头部token，不让会报CORS的错误
    request.headers['token'] = vm.$store.state.basicInfo.userInfo.token || request.headers.token || ''
  }
  return request
})
// 响应拦截
axios.interceptors.response.use((response) => {
  // 响应后删除请求信息
  // responsePending(response)
  if ('respHeader' in response.data){
    let { resultCode = '', message = '' } = response.data.respHeader

    if(resultCode === 0){
      return Promise.resolve({
        data:response.data.respBody?response.data.respBody.res:'',
        message:response.data.respHeader.message,
        code:response.data.respHeader.resultCode
      })
    } else if ([1011,1012].includes(resultCode)){  // 用户登录验证过期，重定位到登录页面||限制用户重复登录
      store.replaceState(Object.assign({},vm.cloneObject(store.state.reset.initState),{reset:store.state.reset})) // 重置vuex的state
      let redirect = router.currentRoute.name // 防止多次重定位
      vm.$message({
        message:message,
        type:'warning',
        duration:2000,
        onClose(){
          router.push({
            name:'login',
            query:{ redirect }
          })
        }
      })
      return Promise.reject(message)
    } else if(resultCode === 9999){ // 提交数据报错或者后端报错
      if (!message) message = '接口返回缺少message!'
      vm.$message({
        message,
        type:'warning',
        duration:1500
      })
      return Promise.reject({
        data:response.data.respBody?response.data.respBody.res:'',
        message:response.data.respHeader.message,
        code:response.data.respHeader.resultCode
      })
    }
  } else { // 针对新哥那边的接口返回的数据进行格式化
    if(response.data.code === 200){
      return Promise.resolve({
        data:response.data.data,
        msg:response.data.msg,
        count:response.data.count
      })
    } else if(response.config.responseType === 'blob'){
      return Promise.resolve({
        data:response.data,
        headers:response.headers
      })
    }
  }
},(error)=>{
  let message = error.response.data.message||'网络错误'
  if(error.message.includes('timeout')){
    message = '请求超时'
  }
  vm.$message({
    message,
    type:'warning',
    duration:2000
  })
  return Promise.reject(error)
})

export default axios